<template>
  <div v-if="data.code == 'login'">
    <el-card
        v-if="data.loginMode == 'wechat'"
        :shadow="props.isDialog ? 'never' : 'always'"
        style="width: 598px; height: 686px"
    >
      <div class="flex-column-center">
        <div
            style="margin-top: 56px;font-weight: bold;font-size: 20px;color: #000000;text-align: center;">
          微信扫码安全登录
        </div>
        <div style="margin-top: 24px">
          <img alt="" src="@/assets/images/user/qr-icon.png" style="width: 288px; height: 288px"/>
        </div>
        <div style="margin-top: 29px;width: 454px;border-bottom: 1px solid #ebebeb;"></div>
        <div class="flex-all-center" style="padding-top: 53px">
          <div
              class="flex-all-center"
              style="cursor: pointer"
              @click="switchLoginMode('code')"
          >
            <img
                alt=""
                src="@/assets/images/user/mobile-icon.png"
                style="width: 16px; height: 20px"/>
            <span style="margin-left: 5px;font-size: 14px;color: #686a71;font-weight: 400;">短信登录</span>
          </div>
          <div
              style="margin: 0 55px; height: 20px; border-left: 1px solid #ebebeb"></div>
          <div
              class="flex-all-center"
              style="cursor: pointer"
              @click="switchLoginMode('password')"
          >
            <img
                alt=""
                src="@/assets/images/user/user-icon.png"
                style="width: 17px; height: 19px"
            />
            <span
                style="
                margin-left: 5px;
                font-size: 14px;
                color: #686a71;
                font-weight: 400;
              "
            >密码登录</span
            >
          </div>
        </div>
        <div
            style="
            margin-top: 47px;
            font-weight: 400;
            font-size: 14px;
            color: #111111;
          "
        >
          <span
          >扫描即表示同意
            <span style="color: #04addb; cursor: pointer"
            >《网站注册协议》</span
            >
          </span>
        </div>
      </div>
    </el-card>
    <!--
        :shadow="props.isDialog ? 'never' : 'always'"

      -->
    <el-card
        v-else
        shadow="never"
        style="width: 390px; height: 555px">
      <div>
        <div
            class="flex-all-center tw-h-117 font-xl tw-pt-70 tw-pb-12"
            style=" color: #000000;font-weight: 400;">
          <div
              :style="data.loginMode == 'password' ? 'color: #04ADDB' : ''"
              style="cursor: pointer"
              @click="switchLoginMode('password')">
            密码登录
          </div>
          <div class="tw-mx-16" style="height: 20px; border-left: 2px solid #ebebeb"></div>
          <div
              :style="data.loginMode == 'code' ? 'color: #04ADDB' : ''"
              style="cursor: pointer"
              @click="switchLoginMode('code')"
          >
            短信登录
          </div>
        </div>
        <div class="width100">
          <div v-if="data.loginMode == 'password'">
            <el-form ref="passwordLoginRef" :model="loginForm" :rules="rules">
              <el-form-item class="tw-h-52" label="" prop="mobile">
                <el-input
                    v-model="loginForm.mobile"
                    placeholder="手机号/用户名"
                    style="width: 100%"
                ></el-input>
              </el-form-item>
              <el-form-item class="tw-h-52" label="" prop="password" style="margin-top: 30px">
                <el-input
                    v-model="loginForm.password"
                    placeholder="请输入您的密码"
                    style="width: 100%;"
                    type="password"
                ></el-input>
              </el-form-item>
            </el-form>
            <div class="tw-pt-20 ">
              <el-button
                  class="footer-button"
                  color="#04ADDB"
                  @keydown.enter="submit('login')"
                  @click="submit('login')"
              >{{ "立即登录" }}
              </el-button>
            </div>
          </div>
          <div v-if="data.loginMode == 'code'">
            <el-form ref="codeLoginRef" :model="loginForm" :rules="rules">
              <el-form-item label="" prop="mobile">
                <el-input
                    v-model="loginForm.mobile"
                    placeholder="请输入手机号"
                    style="width: 100%"
                ></el-input>
              </el-form-item>
              <div class="flex-start" style="width: 100%; margin-top: 30px;height: 52px;margin-bottom: 18px">
                <div>
                  <el-form-item label="" prop="captchaCode">
                    <el-input
                        v-model="loginForm.captchaCode"
                        placeholder="请输入短信验证码"
                        style="width: 248px"
                    ></el-input>
                  </el-form-item>
                </div>
                <div style="margin-left: 11px; width: 166px">
                  <el-button
                      :disabled="countdownVisible"
                      class="footer-button"
                      color="#04ADDB"
                      style="font-size: 14px"
                      @click="getLoginCaptcha('login', 'pcSource')"
                  >{{
                      countdownVisible
                          ? countDown + "秒后可重发"
                          : "获取短信验证码"
                    }}
                  </el-button>
                </div>
              </div>
            </el-form>
            <div class="tw-pt-20">
              <el-button
                  class="footer-button"
                  color="#04ADDB"
                  @click="submit('login')"
              >{{ "立即登录" }}
              </el-button>
            </div>
          </div>
          <div style="margin-top: 56px">
            <!--                  <div v-if="!data.isWechatLogin" class="normal-text flex-all-center" style="width: 100%;text-align: center;cursor: pointer">-->
            <!--                    <img style="width: 20px;height: 20px" src="@/assets/images/user/wechat-icon.png" alt="">-->
            <!--                    <span style="margin-left: 6px;" @click="switchLoginMode('wechat')">微信扫码登录</span>-->
            <!--                  </div>-->
            <div
                v-if="data.loginMode == 'code'"
                class=" flex-all-center "
                style="margin-top: 27px; "
            >
              <span
                  class="tw-text-[#686a71] font-mini">提示：未注册建合网校账号的手机号，登录时将自动注册，且代表您已同意
                <span
                    style="color: #04addb; cursor: pointer"
                    @click="goAgreement(4)"
                >《网站注册协议》</span
                >
              </span>
            </div>
          </div>
          <div
              v-if="data.loginMode == 'password'"
              class="flex-all-center font-mini"
              style="margin-top: 27px;font-weight: 400;"
          >
            <span
                class="tw-text-[#686a71]">登录表示同意
              <span
                  style="color: #04addb; cursor: pointer"
                  @click="goAgreement(4)">《用户协议》</span>
              <span>和</span>
              <span style="color: #04addb; cursor: pointer" @click="goAgreement(5)">《隐私政策》</span>
            </span>
          </div>
        </div>
      </div>
      <div v-if="props.isDialog" class="flex-end" style="margin: 24px 0 0 0; font-size: 12px">
        <span>还没有账号? </span>
        <span style="color: #04addb; cursor: pointer" @click="goRegisterOrLogin('register')">立即注册></span>
      </div>
    </el-card>
  </div>
  <div v-if="data.code == 'register'">
    <el-card v-if="data.registerMode == 'code'" shadow="never" style="width: 390px; height: 555px">

      <div
          class="flex-all-center tw-h-117 font-xl tw-pt-70 tw-pb-12"
          style=" color: #333333;font-weight: 400;">
        <div>
          注册账号
        </div>
      </div>
      <div style="width: 100%;">
        <div>
          <el-form ref="registerRef" :model="registerForm" :rules="rules">
            <el-form-item label="" prop="mobile">
              <el-input
                  v-model="registerForm.mobile"
                  placeholder="请输入手机号"
                  style="width: 100%"
              ></el-input>
            </el-form-item>
            <div class="flex-start" style="width: 100%; margin-top: 30px">
              <div>
                <el-form-item label="" prop="captchaCode">
                  <el-input
                      v-model="registerForm.captchaCode"
                      placeholder="请输入短信验证码"
                      style="width: 248px"
                  ></el-input>
                </el-form-item>
              </div>
              <div style="margin-left: 11px; width: 166px">
                <el-button
                    :disabled="countdownVisible"
                    class="footer-button"
                    color="#04ADDB"
                    style="font-size: 14px"
                    @click="getLoginCaptcha('register', 'pcSource')"
                >{{
                    countdownVisible
                        ? countDown + "秒后可重发"
                        : "获取短信验证码"
                  }}
                </el-button>
              </div>
            </div>
          </el-form>
          <div class="tw-pt-20">
            <el-button class="footer-button" color="#04ADDB" @click="submit('register')">{{ "立即注册" }}
            </el-button>
          </div>
        </div>
        <div style="margin-top: 56px">
          <!--                  <div class="normal-text flex-all-center" style="width: 100%;text-align: center;cursor: pointer">-->
          <!--                    <img style="width: 20px;height: 20px" src="@/assets/images/user/wechat-icon.png" alt="">-->
          <!--                    <span style="margin-left: 6px;" @click="switchRegisterMode('wechat')">微信扫码注册</span>-->
          <!--                  </div>-->
          <div class="normal-text flex-all-center" style="margin-top: 27px; font-size: 12px">
            <span>注册表示同意
              <span style="color: #04addb; cursor: pointer" @click="goAgreement(4)">《用户协议》</span>
              <span>和</span>
              <span style="color: #04addb; cursor: pointer" @click="goAgreement(5)">《隐私政策》</span>
            </span>
          </div>
        </div>
      </div>
      <div v-if="props.isDialog" class="flex-end" style="margin: 24px 0 0 0; font-size: 12px">
        <span>已有账号? </span>
        <span style="color: #04addb; cursor: pointer" @click="goRegisterOrLogin('login')">立即登录></span>
      </div>
    </el-card>
    <el-card v-if="data.registerMode == 'wechat'" :shadow="props.isDialog ? 'never' : 'always'"
             style="width: 598px; height: 686px">
      <div class="flex-column-center">
        <div style="
            margin-top: 56px;
            font-weight: bold;
            font-size: 20px;
            color: #000000;
            text-align: center;
          ">
          微信扫码注册
        </div>
        <div style="margin-top: 24px">
          <img alt="" src="@/assets/images/user/qr-icon.png" style="width: 288px; height: 288px"/>
        </div>
        <div style="
            margin-top: 29px;
            width: 454px;
            border-bottom: 1px solid #ebebeb;
          "></div>
        <div style="margin-top: 53px" class="flex-all-center">
          <div class="flex-all-center" style="cursor: pointer" @click="switchRegisterMode('code')">
            <img alt="" src="@/assets/images/user/mobile-icon.png"
                 style="width: 16px; height: 20px"/>
            <span style="
                margin-left: 5px;
                font-size: 14px;
                color: #000000;
                font-weight: 400;
              ">手机号注册</span>
          </div>
        </div>
        <div style="
            margin-top: 47px;
            font-weight: 400;
            font-size: 14px;
            color: #000000;
          ">
          <span>扫描即表示同意
            <span style="color: #04addb; cursor: pointer">《网站注册协议》</span>
          </span>
        </div>
      </div>
    </el-card>
  </div>
  <captcha-dialog
      ref="captchaDialog"
      v-model:visible="captchaDialogVisible"
      @success="handleCaptchaSuccess"
  />
</template>

<script setup>
import {getCurrentInstance, reactive, ref, watch, nextTick} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {getCaptcha, login} from "@/api/user.js";
import {validateMobile} from "@/utils/common.js";
import {storeUserInfo} from "@/utils/auth.js";
import {useStore} from 'vuex';
import CaptchaDialog from '@/views/component/captcha-dialog.vue'
import {postCaptcha} from "../../../api/user";

const store = useStore();

const props = defineProps({
  isDialog: {
    type: Boolean,
    default: false,
  },
  code: {
    type: String,
    default: "login",
  },
});
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();
const code = ref("");
const registerRef = ref(null);
const passwordLoginRef = ref(null);
const codeLoginRef = ref(null);
const registerForm = reactive({
  mobile: "",
  captchaCode: "",
  // thirdPartyId: ''
  // sourceType: ''
});
const loginForm = reactive({
  mobile: "",
  password: "",
  captchaCode: "",
  uuid: "",
  // thirdPartyId: ''
  // sourceType: ''
});
const countdownVisible = ref(false);
const countDown = ref(60);
const rules = {
  mobile: [
    {required: true, message: "请输入手机号码", trigger: "blur"},
    {pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur"}
  ],
  captchaCode: [
    {required: true, message: "请输入短信验证码", trigger: "blur"},
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    // {validator: validatePassword, trigger: "blur"},
  ],
};

const data = reactive({
  isLogin: true,
  loginMode: "password",
  registerMode: "code",
  dialogVisible: false,
  dialogTitle: "",
  code: "login",
  agreementList: [
    {title: "用户协议", id: null},
    {title: "隐私政策", id: null},
  ],
  tempCaptchaParams: {
    type: '',
    sourceCode: ''
  }
});

const captchaDialogVisible = ref(false);
const captchaDialog = ref(null);

function switchRegisterMode(mode) {
  data.registerMode = mode;
}

function switchLoginMode(mode) {
  loginForm.captchaCode = ''
  loginForm.password = ''
  data.loginMode = mode;
}

function showCaptchaDialog(type, sourceCode) {
  // 获取当前手机号
  const mobile = type === "login" ? loginForm.mobile : registerForm.mobile;

  // 验证手机号是否为空
  if (!mobile) {
    ElMessage.error('请先输入手机号');
    return;
  }

  // 验证手机号格式
  const mobileReg = /^1[3-9]\d{9}$/;
  if (!mobileReg.test(mobile)) {
    ElMessage.error('请输入正确的手机号格式');
    return;
  }

  // 手机号验证通过，显示验证码弹窗
  captchaDialogVisible.value = true;
  // 保存参数供验证后使用
  data.tempCaptchaParams = {
    type,
    sourceCode
  };
}

function getLoginCaptcha(type, sourceCode) {
  // 先显示图形验证码弹窗
  showCaptchaDialog(type, sourceCode);
}

function handleCaptchaSuccess({imageCode, uuid}) {
  const {type, sourceCode} = data.tempCaptchaParams;
  let dataForm = {
    sourceCode: sourceCode,
    mobile: type == "login" ? loginForm.mobile : registerForm.mobile,
    code: imageCode,
    uuid: uuid
  };
  console.log('dataForm:', dataForm);
  postCaptcha(dataForm).then((res) => {
        console.log('res:', res);
        if (res.code === 200) {
          ElMessage.success("操作成功，请留意手机短信");
          captchaDialogVisible.value = false;
          countdownVisible.value = true;
          let codeTime = 60;
          let codeSetInterval = setInterval(() => {
            codeTime--;
            countDown.value = codeTime;
            if (codeTime === 0) {
              clearInterval(codeSetInterval);
              countdownVisible.value = false;
              countDown.value = 60;
            }
          }, 1000);
        } else {
          ElMessage.error(res.msg);
          captchaDialog.value.refreshCode();
        }
      }
  );
}

function goRegisterOrLogin(code) {
  data.code = code;
  code == "register" ? clearRegisterForm() : clearLoginForm();
}

function submit(type) {
  let loginModeMap = {
    password: proxy.$refs.passwordLoginRef,
    code: proxy.$refs.codeLoginRef,
  };
  if (type == "register") {
    proxy.$refs.registerRef.validate((valid) => {
      if (valid) {
        login(
            registerForm,
            (res) => {
              ElMessage.success("注册成功");
              store.commit('acitonsIsLogin', true);
              store.dispatch('acitonsIsLogin', true);

              storeUserInfo(res.data);
              router.push({
                name: "Home",
              });
            },
            (err) => {
              ElMessage.error(err.msg);
            },
        );
      }
    });
  } else if (type == "login") {
    loginModeMap[data.loginMode].validate((valid) => {
      if (valid) {
        login(
            loginForm,
            (res) => {
              ElMessage.success("登录成功");
              store.dispatch('acitonsIsLogin', true);
              storeUserInfo(res.data);
              if (props.isDialog) {
                emit("clickLogin", true);
              } else {
                router.push({
                  name: "Home",
                });
              }
            },
            (err) => {
              ElMessage.error(err.msg);
            },
        );
      }
    });
  }
}

function clearLoginForm() {
  passwordLoginRef.value.resetFields();
  codeLoginRef.value.resetFields();
}

function clearRegisterForm() {
  registerRef.value.resetFields();
}

function goAgreement(id) {
  const {href} = router.resolve({
    path: "/agreement",
    query: {
      id: id,
    },
  });
  window.open(href, "_blank");
}

watch(
    () => props.code,
    (val) => {
      data.code = val;
    },
);
let emit = defineEmits(["clickLogin"]);
</script>
<style lang="scss" scoped>
.footer-button {
  width: 100%;
  height: 52px;
  border-radius: 2px;
  font-size: 18px;
  font-weight: 500;
  color: #ffffff;
}

.normal-text {
  font-weight: 400;
  font-size: 16px;
  color: #686a71;
}
</style>
